﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;

public delegate void CallBack();
public class LoadingScenePage: EventManager
{
    private string loadingTip;
    public Text loadingTipText;
    public Slider processBar;
    public Text loadingPercent;
    public CallBack callBack;
    private AsyncOperation async;
    public string sceneName { get; set; }

    void Start()
    {
        GameObject gameManager = GameObject.Find("StaticSource");     
        if (gameManager.GetComponent<MainLogic>().uiStateManager.GetOldStateID() == (int)GameCore.UIState.UIState_SHLoginState)
        {
            loadingTip = "安全登录中.."; 
        }
        else
        {
            loadingTip = "加载中";
        }
        SetText(loadingTipText, loadingTip);     
    }

    public override void InformationSetting()
    {
        processBar.value = 0;
        StartCoroutine(loadScene());
    }

    /// <summary>  
    /// 加载完场景后就会跳转  
    /// </summary>  
    /// <returns></returns>  
    IEnumerator loadScene()
    { 
        SceneManager.sceneLoaded += delegate { callBack(); };                   

        async = SceneManager.LoadSceneAsync(sceneName);
        Debug.Log("开始加载场景...");
        async.allowSceneActivation = false;
        while (async.progress < 0.9f || processBar.value <0.95)
        {
            yield return new WaitForEndOfFrame();
        }
        loadingTip = "安全系统已启动";
        SetText(loadingTipText, loadingTip);
        processBar.value = 1;
        yield return new WaitForSeconds(0.5f);
        async.allowSceneActivation = true;
    }

    //设置进度条数值函数
    private void SetLoadingProgress(float progress)
    {
        processBar.value += Time.deltaTime/3;
    }

    //设置UI显示百分比
    private void SetPercent(float progress)
    {
        loadingPercent.text = (Math.Floor(processBar.value*100)).ToString()+"%";
    }

    void Update()
    {
        if (async == null)
        {
            return;
        }
        SetLoadingProgress(async.progress);
        SetPercent(async.progress);
    }
}